const express = require("express")
const router = express.Router()
const sqlQuery = require("../mysql/index.cjs")

function URL(arr){
  let url = []
  for (let index = 0; index < arr.length; index++) {
    let el = arr[index];
    let path = "http://127.0.0.1:8081/"
    url.push(path+el)
  }
  return url
}


router.post("/my", (req, res) => {
  let ID = req.body.id;
  // 通过传入的用户id查找用户信息
  let sql = `select * from user where id=${ID}`;
  sqlQuery(sql, (msg => {
    let { name, signature, avatar, sex, } = msg[0]
    let user = msg[0]
    // 在通过用户id查找用户的笔记
    let sql1 = `select * from note where user_id=${ID}`
    sqlQuery(sql1, note => {
      if (note.length != 0) {
        let myNotes = []
        note.forEach(el => {
          let { id, url, title, content, comment_num, support_num, time, user_id } = el
          url = URL(JSON.parse(url))
          let myNote = { name, signature, avatar, sex, id, url, title, content, comment_num, support_num, time, user_id };
          myNotes.push(myNote)
        });
        // 查找用户赞过的笔记
        let sql2 = `select * from support where user_id=${ID}`
        sqlQuery(sql2, support => {
          if (support.length != 0) {
            support.forEach((el) => {
              let sql = `select * from note where id=${el.support_note_id}`
              sqlQuery(sql, (msg) => {
                let list = msg;
                let notes = []
                list.forEach(el => {
                  let sql = `select * from user where id=${el.user_id}`
                  sqlQuery(sql, msg => {
                    let { id, url, title, content, comment_num, support_num, time, user_id } = el
                    url = URL(JSON.parse(url))
                    let { name, signature, avatar, sex, } = msg[0]
                    let note = {
                      id, url, title, content, comment_num, support_num, time,
                      name, signature, avatar, sex, user_id
                    }
                    notes.push(note)
                    // console.log(support.length,index);
                    if (support.length == notes.length) {
                      let data = {
                        user,
                        myNotes,
                        notes,
                      }
                      res.send({
                        status: 100,
                        msg: "成功",
                        data: data
                      })
                    }
                  })
                });
              })
            });
          } else {
            res.send({
              status: 100,
              msg: "成功",
              data: { user, myNotes, notes: [] }
            })
          }
        })
      }else{
        res.send({
          status: 100,
          msg: "成功",
          data: { user, myNotes:[], notes: [] }
        })
      }
    })
  }))
})


module.exports = router